<?php
namespace Home\Controller;

use Think\Controller;

class SmsController extends CommonController
{
  public function __construct()
  {
    parent::__construct();
    Vendor("alisend.TopClient");
    Vendor('AliyunSms.SmsApi');
  }

  /**
   * [发送验证码]
   * @return [type] [description]
   */
  public function send_code()
  {
    $phone = I('phone');
    $type = I('type', 1);
    $app_id = I('app_id');

    if (empty($phone)) {
      return_data("error", "shop_login.phone.blank");
    }

    if (strlen($phone) != 11) {
      return_data("error", "shop_login.phone.eleven.number");
    }
    if (!preg_match("/^1[0-9]{10}$/", $phone)) {
      return_data("error", "shop_login.phone.error");
    }

    $user_id = M("shops")->where("phone=$phone and app_id=$app_id")->getField("id");
    if ($type == 2 && $user_id) {
      return_data("error", "shops.phone.exist");
    }
    if ($type == 1 && !$user_id) {
      return_data("error", "shops.phone.error");
    }

    //一分钟之内只能获取一次
    //判断限制 code的时效性
    //是否超过1分钟
    $sms_info = M("sms_phone")->field('user_id,created_at')->where("phone='$phone'")->order("id desc")->find();
    if ($sms_info) {
      $lasttime = $sms_info['created_at'];
      if ($lasttime> ($this->current_time - 60)) {
        return_data("error", "phone.try.too.little");
      }
    }

    $code = random(6, 1);

    $sms_config = D('apps')->get_sms_config($app_id);
    $sms_reuslt = false;

    if ($sms_config['sms_type'] == 2) {
      $sms = new \SmsApi($sms_config['appkey'], $sms_config['secretKey']);

      $response = $sms->sendSms(
        $sms_config['signname'],
        $sms_config['templatecode'],
        $phone,
        array(
          "code" => $code
        )
      );

      if ($response->Code == 'OK') {
        $sms_reuslt = true;
      }
    } else {
      $c = new \TopClient;
      $c->appkey = $sms_config['appkey'];
      $c->secretKey = $sms_config['secretKey'];
      $req = new \AlibabaAliqinFcSmsNumSendRequest;
      $req->setSmsType("normal");
      $req->setSmsFreeSignName($sms_config['signname']);

      $par['code'] = $code;
      $par=json_encode($par);

      $req->setSmsParam($par);
      $req->setRecNum($phone);
      $req->setSmsTemplateCode($sms_config['templatecode']);
      $resp = $c->execute($req);

      $result = (array)($resp);

      if ($result['code'] < 1) {
        $sms_reuslt = true;
      }
    }

    if ($sms_reuslt) {
      $sms_data = array();
      $sms_data['phone'] = $phone;
      $sms_data['code'] = $code;
      $sms_data['type'] = $type;
      $sms_data['created_at'] = $this->current_time;

      if ($type == 2) {
        $sms_data['notes'] = '商户申请';
      } else {
        $sms_data['notes'] = '商户登陆验证';
      }

      if ($this->user_id) {
        $sms_data['user_id'] = $this->user_id;
      }
      M("sms_phone")->add($sms_data);

      return_data("success", "shop_login.code.success", $code);
    } else {
      return_data("error", "shop_login.code.error");
    }
  }
}
